<?php

namespace app\api\controller;

use app\admin\model\chat\ChatFriend;
use app\admin\model\userstaff\UserClass;
use app\api\validate\ChatValidate;
use app\common\controller\Api;
use think\Config;
use think\Exception;

/**
 * 聊天模块
 *
 */
class Chat extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    protected $failException = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\chat\Chat();
        $this->modelFriend = new ChatFriend();
        $this->modelClass = new UserClass();
        $this->modelUser = new \app\admin\model\userstaff\User();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 获取当前用户通讯录列表
     */
    public function list()
    {
        $userinfo = $this->auth->getUserinfo();      //当前用户id
        $input = input();
        try {
            $pageArr = [
                'page' => 1,
                'page_limit' => 30,
            ];
            $pageArr = array_merge($pageArr, $input);
            $where = [];
            if (!empty($input['keyWord'])){
                $where['name'] = $input['keyWord'];
            }

            //获取当前部门及上下级部门
            $downclassdept = $this->modelClass->where('pid', $userinfo['user_staff_class_id'])->column('id', 'id');
            $topclassdept = $this->modelClass->where('id', $userinfo['user_staff_class_id'])->value('pid');
            $list = $this->modelUser->where('user_staff_class_id', $userinfo['user_staff_class_id'])
                ->whereOr('user_staff_class_id', 'in', $downclassdept)
                ->whereOr('user_staff_class_id', $topclassdept)
                ->where($where)
                ->field('id,mobile,images,status,name')
                ->paginate(['page' => $pageArr['page'] ?: 1, 'list_rows' => $pageArr['page_limit'] ?: 10]);
            $this->success('ok', $list);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 发送聊天内容
     * @return void
     */
    public function add()
    {
        $id = $this->auth->getUserinfo()['staff_id'];
        $input = input('post.');
        $this->validate($input, ChatValidate::class . '.add');
        try {

            $result = $this->model->insertGetId([
                'sender_id' => $id,
                'receive_id' => $input['receive_id'],
                'content' => htmlentities($input['content']),
                'createtime' => time(), 'updatetime' => time()
            ]);
            if (!$result) {
                throw new Exception("写入聊天失败");
            }
            $find = $this->modelFriend
                ->where(['sender_id' => $id, 'receive_id' => $input['receive_id']])
                ->find();
            if (empty($find)) {
                $res = $this->modelFriend->insert([
                    'sender_id' => $id,
                    'receive_id' => $input['receive_id'],
                    'createtime' => time(),
                    'updatetime' => time()
                ]);
                if (!$res) {
                    throw new Exception("写入聊天好友失败");
                }
            }
            $this->success('ok', ['id' => $id, 'receive_id' => $input['receive_id']]);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }


    /**
     * 获取聊天窗口时聊天内容
     * @return void
     */
    public function info()
    {
        $id = $this->auth->getUserinfo()['staff_id'];      //当前用户id
        $input = input('post.');
        $this->validate($input, ChatValidate::class . '.info');
        try {
            $pageArr = [
                'page' => 1,
                'page_limit' => 30,
            ];
            $pageArr = array_merge($pageArr, $input);
            $list = $this->model->alias('c')
                ->join("user_staff s", "c.sender_id=s.id", "left")
                ->join("user_staff r", "c.receive_id=r.id", "left")
                ->where(['c.sender_id' => $id, 'c.receive_id' => $input['receive_id']])
                ->whereOr(['c.sender_id' => $input['receive_id'], 'c.receive_id' => $id])
                ->field(["s.id as sender_id", "s.name as sender_name", "s.images as sender_images", "r.id as receive_id", "r.name as receive_name", "r.images as receive_img", "c.*"])
                ->order('c.sender_id', 'desc')
                ->paginate(['page' => $pageArr['page'] ?: 1, 'list_rows' => $pageArr['page_limit'] ?: 10]);
            $this->model
                ->where('sender_id' ,$id)
                ->where('receive_id',$input['receive_id'])
                ->where('is_read',0)->update(['is_read' => 1]);
            $this->success('ok', $list);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

    }


    /**
     * 消息列表
     * @return void
     */
    public function chat_list()
    {
        $input = input();
        try {
            $pageArr = [
                'page' => 1,
                'page_limit' => 30,
            ];
            $pageArr = array_merge($pageArr, $input);
            $list = $this->modelFriend->alias('c')
                ->where('sender_id',$this->auth->getUserinfo()['staff_id'])
                ->join("user_staff r", "c.receive_id=r.id", "left")
                ->field(["c.sender_id as sender_id", "r.id as receive_id", "r.name as receive_name", "r.images as receive_img", "c.*"])
                ->order('c.sender_id', 'desc')
                ->paginate(['page' => $pageArr['page'] ?: 1, 'list_rows' => $pageArr['page_limit'] ?: 10]);
            foreach ($list->items() as &$v){
                $v['count'] = $this->model
                    ->where('sender_id' ,$v['receive_id'])
                    ->where('receive_id',$v['sender_id'])
                    ->where('is_read',0)
                    ->count('id');
            }
            $this->success('ok',$list);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }

}